<template>
  <!-- 编辑联系人 -->
  <van-contact-card
    type="edit"
    :tel="address.tel"
    :name="address.name"
    @click="toAdressPage"
    v-if="address"
  />

  <!-- 添加联系人 -->
  <van-contact-card type="add" @click="toAdressPage" v-else />

  <!-- 商品信息 -->
  <!-- type为cart 购物车购买-->
  <van-card
    v-for="item in cartlist"
    :key="item.id"
    :price="item.total"
    :title="item.product.name"
    :thumb="item.product.thumbs_text"
    :num="item.nums"
  >
    <template #tags>
      <h4>单价: ￥{{ item.price }}</h4>
    </template>
    <template #desc>
      <div v-if="item.attrs">
        <van-tag
          size="medium"
          type="warning"
          v-for="child in item.attrs"
          style="margin-right: 10px"
          >{{ child.value }}</van-tag
        >
      </div>
      <div v-else>
        <van-tag size="medium" type="danger">无商品规格</van-tag>
      </div>
    </template>
  </van-card>

  <!-- 支付方式 -->
  <van-field
    v-model="payName"
    is-link
    readonly
    label="支付方式"
    placeholder="选择支付方式"
    @click="showPay = true"
  />
  <van-popup v-model:show="showPay" round position="bottom">
    <van-picker
      :columns="columnsPay"
      @cancel="showPay = false"
      @confirm="onPayConfirm"
    />
  </van-popup>

  <!-- 优惠券单元格 -->
  <van-coupon-cell
    :coupons="couponlist"
    :chosen-coupon="chosenCoupon"
    @click="showCoupon = true"
  />
  <!-- 优惠券列表 -->
  <van-popup
    v-model:show="showCoupon"
    round
    position="bottom"
    style="height: 90%; padding-top: 4px"
  >
    <van-coupon-list
      :show-exchange-bar="false"
      :coupons="couponlist"
      :chosen-coupon="chosenCoupon"
      @change="onChange"
    />
  </van-popup>

  <!-- 订单备注 -->
  <van-field
    v-model="remark"
    rows="2"
    autosize
    label="订单备注"
    type="textarea"
    maxlength="120"
    placeholder="请输入留言"
    show-word-limit
  />

  <!-- 提交订单 -->
  <van-submit-bar :price="total" button-text="确认支付" @submit="onSubmit" />
</template>

<script setup>
import { computed } from "vue"

const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.push('/') }
const LoginUser = reactive(proxy.$cookies.get("LoginUser"))
const address = ref(proxy.$cookies.get("address") ?? '')

const cartids = ref(proxy.$route.query.cartids ?? 0)
// 购物车选中的订单列表
const cartlist = ref([])
const showPay = ref(false)
// 用户有的优惠券列表
const couponlist = ref([])
const chosenCoupon = ref(-1);
const showCoupon = ref(false)
// 支付方式绑定值
const payName = ref('')
const pay = ref('')
// 备注
const remark = ref('')

// 支付方式
const columnsPay = [
  { text: '余额', value: 'money' },
  { text: '微信', value: 'wx' },
  { text: '支付宝', value: 'zfb' }
];
// 挂载前加载出数据
onBeforeMount(() => {
  getCartData()
})

const getCartData = async () => {
  // 购物车选中的订单
  let result = await Api.CartIndex({ busid: LoginUser.id, cartids: cartids.value })
  if (result.code == 1) {
    result.data.forEach(item => {
      if (item.attrs) {
        item.attrs = JSON.parse(item.attrs)
      }
    })
    cartlist.value = result.data;
  }

  // 用户有的优惠券列表
  getCoupon()
}


// 获取用户有的优惠券列表
const getCoupon = async () => {
  let res = await Api.CouponBusiness({ busid: LoginUser.id })
  if (res.code == 1) {
    console.log(res.data);
    res.data.forEach(item => {
      couponlist.value.push({
        id: item.id,
        name: item.coupon.title,
        valueDesc: item.coupon.rate * 100,
        unitDesc: '折',
        condition: '正在活动中',
        startAt: parseInt(item.coupon.createtimes),
        endAt: parseInt(item.coupon.endtime),
        rate: item.coupon.rate
      })
    })
  }
}


// 选中支付方式
const onPayConfirm = ({ selectedOptions }) => {
  showPay.value = false;
  payName.value = selectedOptions[0].text
  pay.value = selectedOptions[0].value
}

// 跳转地址页面
const toAdressPage = () => {
  proxy.$router.push({
    path: '/business/address/index',
    query: {
      action: 'order'
    }
  })
}

// 确认订单页面 总价格
let total = computed(() => {
  var count = 0
  count = cartlist.value.reduce((index, item) => index + parseFloat(item.total), 0)

  // 使用优惠券
  if (chosenCoupon.value != -1) {
    let rate = couponlist.value[chosenCoupon.value].rate
    count = parseFloat(count * rate).toFixed(2)
  }

  return parseFloat(count * 100);
})

// 选中优惠券
const onChange = (index) => {
  showCoupon.value = false;
  chosenCoupon.value = index;
  if (index != -1) {
    // 计算总价格
    // reduce通过回调函数来处理数组中的每个元素，累加并返回结果 index为累加器
    var totals = cartlist.value.reduce((index, item) => index + parseFloat(item.total), 0)
    let rate = couponlist.value[index].rate
    // 优惠后的金额
    var price = totals * rate
    // 优惠券显示优惠了多少金额
    var couponPrice = totals - price
    couponPrice = parseFloat(couponPrice * 100).toFixed(2)
    couponlist.value[index].value = couponPrice
    // console.log(couponlist.value);
  }
}


// 提交订单
const onSubmit = async () => {
  let data = {
    busid: LoginUser.id,
    cartids: cartids.value,
    businessaddrid: address.value.id,
    pay: pay.value,
    remark: remark.value,
    couponid: couponlist.value[chosenCoupon.value] ? couponlist.value[chosenCoupon.value].id : 0,
    amount: parseFloat(total.value / 100)
  }

  console.log(data);
  let result = await Api.OrderAdd(data)
  if (result.code == 1) {
    showSuccessToast({
      message: result.msg,
      onClose: function () {
        proxy.$router.push('/business/index')
      }
    })
  } else {
    showFailToast(result.msg);
  }
}

</script>

<style>
.van-submit-bar__text,
.van-card__content,
.van-cell__title {
  text-align: left;
}
.van-card__num{
  text-align: right;
}
</style>